//
//  TTLiveViewController.swift
//  TTProduct
//
//  Created by Toj on 3/19/21.
//  Copyright © 2021 TTProduct. All rights reserved.
//

import Cocoa

enum TTLiveItemStyle: Int {
    case detailed
    case brief
}

private let titleBarHeight: CGFloat = 44
private let toolsHeight: CGFloat = 36
private let teacherHeight: CGFloat = 135
private let liveHeight = TTScreenVisibleHeight - titleBarHeight - teacherHeight - 2 - toolsHeight - 26

class TTLiveViewController: VNViewController, LiveViewModel {
    
    public var students:[TTLiveUser]? {
        didSet {
            teacherItem.model = nil
            collectionView.reloadData()
            setupLogoLocation()
        }
    }
    
    private var lineSpacing: CGFloat = 2
    private var itemSpacing: CGFloat = 0
    private var itemSize: CGSize = .zero
    var itemStyle: TTLiveItemStyle = .detailed {
        didSet {
            if itemStyle == .detailed {
                itemSpacing = 0.01
                itemSize = CGSize(width: 240, height: 135)
            }
            else if itemStyle == .brief {
                itemSpacing = 2
                itemSize = CGSize(width: 119, height: 89)
            }
            collectionView.reloadData()
            setupLogoLocation()
            collectionView.scroll(.zero)
        }
    }
    
    private lazy var teacherItem: TTLiveItem = {
        let item = TTLiveItem()
        return item
    }()
    
    private lazy var toolsView: TTLiveToolsView = {
        let view = TTLiveToolsView()
        view.delegate = self
        view.tt_backgroundColor = NSColor.init(hexColor: "#E0F3FC")
        return view
    }()
    
    private lazy var listView: NSView = {
        let view = NSView()
        view.tt_backgroundColor = .clear
        view.tt_cornerRadius(8)
        return view
    }()
    
    private lazy var logoImageView: NSImageView = {
        let view = NSImageView()
        view.image = NSImage(named: "liveListLogo")
        return view
    }()
    
    private lazy var backgroundImageView: NSImageView = {
        let view = NSImageView()
        view.imageScaling = .scaleAxesIndependently
        view.image = NSImage(named: "liveListBackgroundImage")
        return view
    }()
    
    private lazy var chatVC: TTLiveChatViewController = {
        let vc = TTLiveChatViewController()
        return vc
    }()
    
    private lazy var scrollView: NSScrollView = {
        let view = NSScrollView()
        view.scrollerStyle = .overlay
        view.scrollerKnobStyle = .dark
        view.verticalScrollElasticity = .automatic
        view.documentView = collectionView
        view.tt_shadow(color: NSColor.black.tt_alpha(0.3))
        return view
    }()
    
    private var liveIdentifier = NSUserInterfaceItemIdentifier(rawValue: TTLiveItem.className())
    private lazy var collectionView: NSCollectionView = {
        let view = NSCollectionView(frame: .zero)
        view.dataSource = self
        view.delegate = self
        view.backgroundColors = [NSColor.clear]
        
        let flowLayout = NSCollectionViewFlowLayout()
        flowLayout.scrollDirection = .vertical
        view.collectionViewLayout = flowLayout
        
        view.register(TTLiveItem.self, forItemWithIdentifier: liveIdentifier)
        return view
    }()
    
    private lazy var viewLogic: LiveViewLogic = {
        let logic = LiveViewLogic()
        logic.liveView = self
       return logic
    }()
    
    func addRemote(user: TTLiveUser) {
        
    }
    
    func removeRemote(user: TTLiveUser) {
        
    }
    
    deinit {
        print(#function + className)
    }
}

extension TTLiveViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupMakeAddSubviews()
        
        setupMakeLayoutSubviews()
        
        setupMakeUI()
        
        setupMakeRequest()
    }
    
    override func viewDidAppear() {
        super.viewDidAppear()
        
        setupLogoLocation()
    }
    
    
    private func setupLogoLocation() {
        print(#function)
        let pcount = students?.count ?? 0
        var heightCount = pcount
        if itemStyle == .brief {
            heightCount = ((pcount + 1) / 2)
        }
       
        let logoSize = CGSize(width: 128, height: 113)
        let height = liveHeight - CGFloat(heightCount - 1 ) * lineSpacing - itemSize.height * CGFloat(heightCount)
    
        logoImageView.isHidden = height < logoSize.height
        if logoImageView.isHidden { return }
        
        let y = (height - logoSize.height) * 0.5
        let x = (view.bounds.width - logoSize.width) * 0.5
        
        logoImageView.frame = CGRect(origin: CGPoint(x: x, y: y), size: logoSize)
    }
    
}

// viewLogic
extension TTLiveViewController {
    
    private func setupMakeRequest() {
        let timeTableID = ""
        viewLogic.roomRequest(timeTableID: timeTableID)
    }
}

// MARK: - 点击事件
extension TTLiveViewController {
    
    @objc private func didTapTeacherZoom(sender: NSButton) {
        
    }
}

// MARK: - NSCollectionViewDataSource
extension TTLiveViewController: TTLiveToolsViewDelegate {
    
    func toolsViewDidTapIM(view: TTLiveToolsView) {
        chatVC.view.isHidden = false
        scrollView.isHidden = true
    }
    
    func toolsViewDidTapLives(view: TTLiveToolsView) {
        chatVC.view.isHidden = true
        scrollView.isHidden = false
    }
    
    func toolsViewDidTapSwitch(button: TTButton) {
        itemStyle = button.tt_selected ? .brief : .detailed
    }
}

// MARK: - NSCollectionViewDataSource
extension TTLiveViewController: NSCollectionViewDataSource {
    func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
        return students?.count ?? 0
    }
    
    func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
        let model = students?[indexPath.item]
        let item = collectionView.makeItem(withIdentifier: liveIdentifier, for: indexPath) as! TTLiveItem
        item.style = itemStyle
        item.model = model
        return item
    }
}

// MARK: - NSCollectionViewDelegate
extension TTLiveViewController: NSCollectionViewDelegate {
    
}

// MARK: - setup
extension TTLiveViewController: NSCollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> NSSize {
        return itemSize
    }
    
    func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return lineSpacing
    }
    
    func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return itemSpacing
    }
    
    func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, insetForSectionAt section: Int) -> NSEdgeInsets {
        
        return NSEdgeInsetsZero
    }
}

// MARK: - setup
extension TTLiveViewController {
    
    private func setupMakeAddSubviews() {
        addChild(teacherItem)
        addChild(chatVC)
        
        view.addSubview(teacherItem.view)
        view.addSubview(listView)
        view.addSubview(toolsView)
        
        listView.addSubview(backgroundImageView)
        listView.addSubview(logoImageView)
        listView.addSubview(scrollView)
        listView.addSubview(chatVC.view)
    }
    
    private func setupMakeLayoutSubviews() {
        teacherItem.view.snp.makeConstraints { (make) in
            make.left.right.top.equalTo(view)
            make.height.equalTo(teacherHeight)
        }
        
        toolsView.snp.makeConstraints { (make) in
            make.left.right.equalTo(teacherItem.view)
            make.top.equalTo(teacherItem.view.snp.bottom).offset(1)
            make.height.equalTo(toolsHeight)
        }
        
        listView.snp.remakeConstraints { (make) in
            make.right.left.bottom.equalTo(view)
            make.top.equalTo(toolsView.snp.bottom).offset(-8)
        }
        
        backgroundImageView.snp.remakeConstraints { (make) in
            make.edges.equalTo(view)
        }
        
        scrollView.snp.makeConstraints { (make) in
            make.top.equalTo(toolsView.snp.bottom)
            make.width.bottom.left.equalTo(listView)
        }
        
        chatVC.view.snp.makeConstraints { (make) in
            make.edges.equalTo(scrollView)
        }
    }
    
    private func setupMakeUI() {
        students = nil
        itemStyle = .detailed
        teacherItem.view.tt_backgroundColor = .red
        
        teacherItem.model = nil
    }
}
